package com.lixx.usercenter.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lixx.usercenter.common.BaseResponse;
import com.lixx.usercenter.common.ErrorCode;
import com.lixx.usercenter.exception.BusinessException;
import com.lixx.usercenter.model.domain.User;
import com.lixx.usercenter.model.domain.request.*;
import com.lixx.usercenter.services.UserService;
import com.lixx.usercenter.utils.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import static com.lixx.usercenter.contant.UserConstant.ADMIN_ROLE;
import static com.lixx.usercenter.contant.UserConstant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
public class userController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求
     * @return long
     * @author Lixx
     * @date 2025/08/05
     */

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);

        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录请求
     * @param request          请求
     * @return {@link User }
     * @author Lixx
     * @date 2025/08/05
     */

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);

        }
        User safetyUser = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(safetyUser);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return {@link Integer }
     * @author Lixx
     * @date 2025/08/05
     */

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Integer result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 插入用户
     *
     * @param userAddRequest 用户添加请求
     * @param request        请求
     * @return {@link Long }
     * @author Lixx
     * @date 2025/08/05
     */

    @PostMapping("/insert")
    public BaseResponse<Long> insertUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        // 鉴权
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long result = userService.insertUser(userAddRequest, request);
        return ResultUtils.success(result);
    }

    @DeleteMapping("/delete/{id}")
    public BaseResponse<Integer> deleteUser(@PathVariable Long id, HttpServletRequest request) {
        // 鉴权
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer result = userService.deleteUser(id, request);
        return ResultUtils.success(result);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest 用户更新请求
     * @param request           请求
     * @return {@link Integer }
     * @author Lixx
     * @date 2025/08/05
     */

    @PutMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        // 鉴权
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (userUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        Integer result = userService.updateUser(userUpdateRequest, request);
        return ResultUtils.success(result);
    }

    /**
     * 列出用户
     *
     * @param userQueryRequest 用户查询请求
     * @return {@link Page }<{@link User }>
     * @author Lixx
     * @date 2025/08/07
     */

    @PostMapping("/list/page")
    public BaseResponse<Page<User>> listUser(@RequestBody UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        Page<User> userPage = userService.listUser(userQueryRequest);
        return ResultUtils.success(userPage);
    }

    /**
     * 获取当前用户
     * @param request 请求
     * @return {@link BaseResponse }<{@link User }>
     * @author Lixx
     * @date 2025/08/10
     */

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        // 判空
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Long userId = currentUser.getId();
        User user = userService.getById(userId);
        User safeUser = userService.getSafeUser(user);
        return ResultUtils.success(safeUser);
    }

    /**
     * 判断是否为管理员
     *
     * @param request 请求
     * @return boolean
     * @author Lixx
     * @date 2025/08/09
     */
    public boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user == null || user.getUserRole() != ADMIN_ROLE) {
            return false;
        }
        return true;
    }
}
